package com.zlm.filter;


import com.zlm.exception.KaptchaNotMatchException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 自定义验证码过滤器
 */

//@Component 这里不能在 不然无法进行额外的配置
public class VerifyCodeFilter extends UsernamePasswordAuthenticationFilter {

    private static final String FORM_KAPTCHA_KEY = "verifyCode";

    private String kaptchaParameter = FORM_KAPTCHA_KEY;

    // 直接获取
    public String getKaptchaParameter() {
        return kaptchaParameter;
    }

    // 你可以在配置的时候赋值
    public void setKaptchaParameter(String kaptchaParameter) {
        this.kaptchaParameter = kaptchaParameter;
    }

    /**
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        // 判断是不是POST请求
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        // 页面输入的
        String verifyCode = request.getParameter(getKaptchaParameter());

        HttpSession session = request.getSession();
        // session里面的
        String sessionVerifyCode = (String) session.getAttribute("verifyCode");

        if (!StringUtils.isEmpty(verifyCode) && !StringUtils.isEmpty(sessionVerifyCode)
                && verifyCode.equalsIgnoreCase(sessionVerifyCode)) {
            // 这样的话就是验证码相等
            // 就可以去父类里面实现了，因为原本就是在这里弄个验证码判定的
            return super.attemptAuthentication(request, response);
        }
        throw new KaptchaNotMatchException("验证码不匹配");

    }
}
